let tempDataList = [];
let pageNum = 1;
let pageSize = 10;
let scrollContainer = document.getElementById('scrollContainer');
let lastLoadStatus = true;
let lastKeyWord = '';
let selectCompanyName = sessionStorage.getItem('selectCompanyName');
let selectCompanyId = sessionStorage.getItem('selectCompanyId');

$(function () {
    $('.page-header').html(selectCompanyName + ' - ' + $('.page-header').html());
    $("#selectItem").val(sessionStorage.getItem("deviceKeyWord"));

    // 自动加载设备列表信息
    loadDeviceData();

    // 无限滚动
    $('.mainContent').on('scroll', function () {
        const scrollTop = scrollContainer.scrollTop;
        const scrollHeight = scrollContainer.scrollHeight;
        const clientHeight = scrollContainer.clientHeight;

        if (lastLoadStatus && (scrollTop + clientHeight >= scrollHeight - 50)) {
            lastLoadStatus = false;
            pageNum++;
            loadDeviceData();
        }
    });
})

function loadDeviceData() {
    // 加载设备信息
    showLoading();

    const keyWord = $("#selectItem").val();

    if (keyWord.trim().length > 0 && keyWord !== lastKeyWord) pageNum = 1;

    lastKeyWord = keyWord;

    // 先根据公司ID和用户ID加载出所有的设备列表
    // type为1=该公司的总体情况报告，2=制定某个设备的情况报告，3=指定某个设备的指定参数的情况报告
    $.post(serverUrl + ':' + serverPort + serverName + '/companyUser/iFindDeviceListByUserId', {
        userId: sessionStorage.getItem("loginUserId"), companyId: selectCompanyId, keyWord: keyWord, pageNum: pageNum, pageSize: pageSize
    }, function (result) {
        hideLoading();

        let obj = JSON.parse(result);

        tempDataList = tempDataList.concat(obj.data.content);
        renderData(tempDataList);

        lastLoadStatus = true;
    });
}

// 渲染底部显示数据
function renderData(dataList) {
    let content = '';

    $.each(dataList, function (i, item) {
        content += '<div class="card" onclick="toAlarmRulePage(\'' + item.code + '\',\'' + item.company.name + ' - ' + item.name + '\')">';
        content += '<div class="card-content">';

        if (item.company.name.length > 0) {
            content += '<div class="card-title">' + item.company.name + ' - ' + item.name;
        } else {
            content += '<div class="card-title">' + item.name;
        }

        if (item.onlineStatus === 1) {
            content += '<span class="user-gender gender-male">在线</span>';
        } else {
            content += '<span class="user-gender gender-female">离线</span>';
        }

        content += '</div>';
        content += '<div class="switch-group">';
        content += '<div class="switch-item">';

        if (null !== item.lastOnlineTime && item.lastOnlineTime !== '') {
            content += '<span class="switch-label">最后在线时间：' + formatTime(item.lastOnlineTime) + '</span>';
        } else {
            content += '<span class="switch-label">最后在线时间：暂无</span>';
        }

        content += '</div></div></div></div>';
    });

    $('.mainContent').html(content);
}

function toAlarmRulePage(deviceCode, deviceName) {
    // 跳转到设备设备关联关系管理界面
    sessionStorage.setItem('selectDeviceCode', deviceCode);
    sessionStorage.setItem('selectDeviceName', deviceName);
    sessionStorage.setItem('deviceKeyWord', $("#selectItem").val());

    window.location.href = 'wx/center/alarmRule';
}

// 获取DOM元素
const userInput = document.getElementById('selectItem');

// 状态变量
let isComposing = false; // 用于检测中文输入状态
let lastValue = ''; // 上次保存的值

// 内容变化处理函数（防抖后）
function handleContentChange() {
    const currentValue = userInput.value;

    // 内容实际发生变化时才处理
    if (currentValue !== lastValue) {
        lastValue = currentValue;
        tempDataList = [];
        loadDeviceData();
    }
}

// 创建防抖函数
function debounce(func, delay) {
    let timer;
    return function () {
        clearTimeout(timer);
        timer = setTimeout(() => {
            func.apply(this, arguments);
        }, delay);
    };
}

// 创建500ms防抖的内容变化处理器
const debouncedChangeHandler = debounce(handleContentChange, 500);

// 事件监听
userInput.addEventListener('input', function () {
    // 中文输入过程中不触发
    if (!isComposing) {
        debouncedChangeHandler();
    }
});

// 处理中文输入法事件
userInput.addEventListener('compositionstart', function () {
    isComposing = true;
});

userInput.addEventListener('compositionend', function () {
    isComposing = false;
    debouncedChangeHandler(); // 中文输入完成，触发变化检测
});